<template>
  <a-modal
    title="填写箱号、封号"
    :width="1250"
    centered
    :visible="visible"
    @ok="handleOk"
    @cancel="handleCancel"
    destoryOnClose
  >
    <p>
      <img src="../../../static/images/tshi.png" style="float:left; margin-right:5px;" />一行填写一个箱子的箱号、封号，填写后在拆分的订单中，自动使用该填写的箱号、封号
    </p>
    <a-form-model ref="form" :label-col="{span:3}" :wrapper-col="{span:18}" style="margin-top:20px">
      <a-form-model-item label="Excel表格导入">
        <a-row>
          <a-col :span="18">
            <a-upload-dragger
              accept=".xls, .xlsx"
              :action="uploadUrl"
              :headers="headers"
              :beforeUpload="beforeUpload"
              :file-list="fileList"
              @change="handleChange"
            >
              <p class="ant-upload-drag-icon">
                <a-icon type="inbox" />
              </p>
              <p class="ant-upload-text">上传Excel文件</p>
            </a-upload-dragger>
          </a-col>
          <a-col :span="4" :offset="1">
            <a-button ghost type="primary" @click="download" style="margin-top:95px">下载模板</a-button>
          </a-col>
        </a-row>
      </a-form-model-item>
    </a-form-model>
    <a-table
      :columns="columns"
      :data-source="dataInit"
      :pagination="false"
      :maskClosable="false"
      size="middle"
      :row-class-name="record => (record.canImport === 0) ? 'redRow' : ''"
      :row-key="(record,index) => index"
    >
      <template
        v-for="col in ['containerNo', 'containerSealNo', 'holderId', 'seagoingShipName', 'seagoingShipVoyage', 'seagoingShipOrderCode']"
        :slot="col"
        slot-scope="text, record"
      >
        <div v-if="col === 'holderId'" :key="col">
          <a-select
            :value="text"
            @change="e => selectChange(e, record.orderId, col)"
            style="width:180px"
          >
            <a-select-option v-for="v in holderNameList" :key="v.id">{{v.name}}</a-select-option>
          </a-select>
        </div>
        <div v-else :key="col">
          <a-input :value="text" @change="e => selectChange(e.target.value, record.orderId, col)" />
        </div>
      </template>
    </a-table>
  </a-modal>
</template>

<script>
import { queryHolderNameList } from '@/api'
import { queryIsExistContainerNo } from '@/api/orderCenter'
import { VERSION_NO, APP_KEY, REQUEST_INTEFACE_URL } from '@/common/config'
import { commonExport } from '@/api/request'
import md5 from 'md5'
import store from 'store'
import Util from '@/common/util'
const createArray = size => {
  const arr = []
  for (let i = 0; i < size; i++) {
    arr.push({})
  }
  return [...arr]
}

export default {
  name: 'box-title-no',
  props: {
    visible: Boolean,
    data: {
      type: Array,
      default () {
        return []
      }
    },
    size: Number
  },
  data () {
    const columns = [
      {
        title: '序号',
        width: '60px',
        customRender: (text, record, index) => {
          return index + 1
        }
      },
      {
        title: '箱号',
        dataIndex: 'containerNo',
        scopedSlots: { customRender: 'containerNo' }
      },
      {
        title: '封号',
        dataIndex: 'containerSealNo',
        scopedSlots: { customRender: 'containerSealNo' }
      },
      {
        title: '持箱人',
        dataIndex: 'holderId',
        scopedSlots: { customRender: 'holderId' }
      },
      {
        title: '船名',
        dataIndex: 'seagoingShipName',
        scopedSlots: { customRender: 'seagoingShipName' }
      },
      {
        title: '航次',
        dataIndex: 'seagoingShipVoyage',
        scopedSlots: { customRender: 'seagoingShipVoyage' }
      },
      {
        title: '运单号',
        dataIndex: 'seagoingShipOrderCode',
        scopedSlots: { customRender: 'seagoingShipOrderCode' }
      }
    ]
    return {
      columns,
      dataInit: [],
      holderNameList: [],
      uploadUrl: REQUEST_INTEFACE_URL + '/order/previewImportContainerNoExcel',
      headers: {},
      fileList: [],
      file: {}
    }
  },
  methods: {
    holderNameListRequest (e) {
      queryHolderNameList(e)
        .then(res => {
          this.holderNameList = res.data
        })
        .catch(rs => {})
    },
    isExistContainerNoRequest (e, dataSource) {
      queryIsExistContainerNo(e)
        .then(res => {
          // console.log(res)
          if (res.code === 0) {
            if (res.data.isExist) {
              this.$message.error(`箱号${res.data.list.join(',')}已存在！`)
              return false
            }
            this.$emit('setVisible', dataSource)
          }
        })
        .catch(rs => {})
    },
    download () {
      commonExport('/common/downloadExcelTemplate', {
        name: '订单审核封箱号导入模板.xls'
      })
    },
    beforeUpload (file) {
      let self = this
      let fileLength = self.fileList.length
      return new Promise((resolve, reject) => {
        if (fileLength > 0) {
          self.$message.error('Excel文件已存在！')
          reject(new Error(false))
        } else {
          const uuid = Util.getUUID()
          const headers = {
            appKey: APP_KEY,
            version: VERSION_NO,
            timestamp: (() => new Date().getTime())(),
            nonce: uuid,
            token: store.get('token') ? store.get('token') : '',
            sign: md5(
              `appKey${APP_KEY}nonce${uuid}timestamp${new Date().getTime()}84001ac0d7064aea883e8f6623ceb82b`
            ).toUpperCase()
          }
          self.headers = headers
          resolve()
        }
      })
    },
    handleChange ({ file, fileList }) {
      this.fileList = fileList
      this.file = file
      // // console.log(fileList)
      // // console.log(file)
      if (file.status === 'done') {
        // this.billInfo = file.response.data.rsp
        let list = file.response.data
        // // console.log(this.size)
        // // console.log(list)
        list.forEach((v, k) => {
          v.orderId = k
        })
        if (list.length > this.size) {
          this.dataInit = list.splice(0, this.size)
        } else {
          this.dataInit.splice(0, list.length, ...list)
        }
        // // console.log(file)
        // // console.log(file.response.data)
      } else if (file.status === 'removed') {
        // // console.log(this.size)
        this.dataInit.forEach(v => {
          v.holderId = ''
          v.containerNo = ''
          v.containerSealNo = ''
          v.seagoingShipName = ''
          v.seagoingShipVoyage = ''
          v.seagoingShipOrderCode = ''
          v.canImport = 1
        })
        this.fileList = []
        this.file = []
      }
    },
    selectChange (value, orderId, column) {
      // // console.log(value)
      const newData = [...this.dataInit]
      const target = newData.filter(item => orderId === item.orderId)[0]
      if (target) {
        target[column] = value
        this.dataInit = newData
      }
    },
    handleOk () {
      let _self = this
      let dataSource = _self.dataInit
      let nameList = []
      dataSource.forEach(v => {
        v.containerNo = v.containerNo.toUpperCase().replace(/[^a-zA-Z0-9]/g, '')
      })
      for (let i = 0; i < dataSource.length; i++) {
        // dataSource[i].containerNo = dataSource[i].containerNo.toUpperCase().replace(/[^a-zA-Z0-9]/g, '')
        if (
          !dataSource[i].containerNo ||
          !dataSource[i].containerSealNo ||
          !dataSource[i].holderId
        ) {
          _self.$message.error('信息填写不完整！')
          return false
        } else if (dataSource[i].canImport === 0) {
          _self.$message.error(`${dataSource[i].reason}`)
          return false
        } else {
          nameList.push(dataSource[i].containerNo)
        }
      }
      if (new Set(nameList).size !== nameList.length) {
        _self.$message.error('箱号填写相同！')
        return false
      }
      // nameList.forEach(v => {
      //   v = v.toUpperCase().replace(/[^a-zA-Z0-9]/g, '')
      // })
      this.isExistContainerNoRequest({ nameList: nameList }, dataSource)
    },
    handleCancel () {
      this.dataInit = []
      this.fileList = []
      this.file = []
      this.$emit('setVisible', false)
    }
  },
  watch: {
    visible () {
      if (this.visible) {
        if (this.size >= 0) {
          let newData = [...this.data]
          let len = newData.length
          // // console.log(this.size)
          if (this.size > len) {
            newData = newData.concat(createArray(this.size - len))
          } else {
            newData = newData.filter((v, i) => i < this.size)
          }
          this.dataInit = newData.map((v, i) => {
            return {
              orderId: i + 1,
              holderId: v.holderId || '',
              containerNo: v.containerNo || '',
              containerSealNo: v.containerSealNo || '',
              seagoingShipName: v.seagoingShipName || '',
              seagoingShipVoyage: v.seagoingShipVoyage || '',
              seagoingShipOrderCode: v.seagoingShipOrderCode || ''
            }
          })
        }
      }
    }
  },
  mounted () {
    this.holderNameListRequest({ status: 1 })
  }
}
</script>

<style>
.redRow {
  background: tomato;
}
</style>
